﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Sunny.UI;

namespace RclSystem
{
    public partial class DeliveryInvoice : UIPage
    {
        DataTable dataTable = new DataTable("DataTable");
        public DeliveryInvoice()
        {
            InitializeComponent();
            uiDataGridView1.AutoGenerateColumns = false;
        }


        private void ListQuery()
        {
            dataTable.Rows.Clear();
            uiDataGridView1.Rows.Clear();
            string extsql = "";
            if(txt_saleman.TextLength != 0)
            {
                extsql += " salesman = '" + txt_saleman.Text.Trim() + "'";
            }
            if(txt_company.TextLength != 0)
            {
                extsql += " and companyname like '%" + txt_company.Text + "%'";
            }
            dataTable = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_delivery where deliverdate >= '" + dt_qstart.Value.ToString("yyyy-MM-dd")
                + "' and deliverdate <= '" + dt_qend.Value.ToString("yyyy-MM-dd") + "'" + extsql + " order by deliverdate desc");

            int index = 0;
            double salecount_total = 0;
            double saleamount_total = 0;
            double remainamount_total = 0;
            double bsalary_total = 0;
            double settlement_total = 0;
            double interestsubsidy_total = 0;
            double tcamount_total = 0;

            foreach (DataRow row in dataTable.Rows)
            {
                index = this.uiDataGridView1.Rows.Add();
                this.uiDataGridView1.Rows[index].Cells[0].Value = row["id"].ToString();
                this.uiDataGridView1.Rows[index].Cells[1].Value = row["salesman"].ToString();
                this.uiDataGridView1.Rows[index].Cells[2].Value = row["companyname"].ToString();
                this.uiDataGridView1.Rows[index].Cells[3].Value = ((DateTime)row["deliverdate"]).ToString("yyyy-MM-dd");
                this.uiDataGridView1.Rows[index].Cells[4].Value = row["salecount"].ToString();
                this.uiDataGridView1.Rows[index].Cells[5].Value = row["saleamount"].ToString();
                this.uiDataGridView1.Rows[index].Cells[6].Value = row["remainamount"].ToString();
                this.uiDataGridView1.Rows[index].Cells[7].Value = row["perton"].ToString();
                this.uiDataGridView1.Rows[index].Cells[8].Value = row["bsalary"].ToString();
                this.uiDataGridView1.Rows[index].Cells[9].Value = row["accountdays"].ToString();
                this.uiDataGridView1.Rows[index].Cells[10].Value = ((DateTime)row["duedate"]).ToString("yyyy-MM-dd");
                this.uiDataGridView1.Rows[index].Cells[11].Value = row["settlement"].ToString();
                this.uiDataGridView1.Rows[index].Cells[12].Value = row["interestsubsidy"].ToString();
                this.uiDataGridView1.Rows[index].Cells[13].Value = row["tcamount"].ToString();
                this.uiDataGridView1.Rows[index].Cells[14].Value = ((DateTime)row["create_time"]).ToString("yyyy-MM-dd HH:mm:ss");

                salecount_total += double.Parse(row["salecount"].ToString());
                saleamount_total += double.Parse(row["saleamount"].ToString());
                remainamount_total += double.Parse(row["remainamount"].ToString());
                bsalary_total += double.Parse(row["bsalary"].ToString());
                settlement_total += double.Parse(row["settlement"].ToString());
                interestsubsidy_total += double.Parse(row["interestsubsidy"].ToString());
                tcamount_total += double.Parse(row["tcamount"].ToString());
            }
            index = this.uiDataGridView1.Rows.Add();
            this.uiDataGridView1.Rows[index].Cells[0].Value = "";
            this.uiDataGridView1.Rows[index].Cells[1].Value = "合计";
            this.uiDataGridView1.Rows[index].Cells[2].Value = "";
            this.uiDataGridView1.Rows[index].Cells[3].Value = "";
            this.uiDataGridView1.Rows[index].Cells[4].Value = Math.Round(salecount_total, 3);
            this.uiDataGridView1.Rows[index].Cells[5].Value = Math.Round(saleamount_total, 2);
            this.uiDataGridView1.Rows[index].Cells[6].Value = Math.Round(remainamount_total, 2);
            this.uiDataGridView1.Rows[index].Cells[7].Value = "";
            this.uiDataGridView1.Rows[index].Cells[8].Value = Math.Round(bsalary_total, 2);
            this.uiDataGridView1.Rows[index].Cells[9].Value = "";
            this.uiDataGridView1.Rows[index].Cells[10].Value = "";
            this.uiDataGridView1.Rows[index].Cells[11].Value = Math.Round(settlement_total, 2);
            this.uiDataGridView1.Rows[index].Cells[12].Value = Math.Round(interestsubsidy_total, 2);
            this.uiDataGridView1.Rows[index].Cells[13].Value = Math.Round(tcamount_total, 2);
            this.uiDataGridView1.Rows[index].Cells[14].Value = "";
            uiDataGridView1.ClearSelection();
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            DeliveryDialog frm = new DeliveryDialog();
            frm.Render();
            frm.ShowDialog();
            if (frm.IsOK)
            {
                Dictionary<string, object> data = new Dictionary<string, object>();
                data.Add("salesman", frm.DeliveryEntity.salesman);
                data.Add("companyname", frm.DeliveryEntity.companyname);
                data.Add("deliverdate", frm.DeliveryEntity.deliverdate);
                data.Add("salecount", frm.DeliveryEntity.salecount);
                data.Add("saleamount", frm.DeliveryEntity.saleamount);
                data.Add("remainamount", frm.DeliveryEntity.saleamount);
                data.Add("perton", frm.DeliveryEntity.perton);
                data.Add("bsalary", frm.DeliveryEntity.bsalary);
                data.Add("accountdays", frm.DeliveryEntity.accountdays);
                data.Add("duedate", frm.DeliveryEntity.duedate);
                data.Add("settlement", frm.DeliveryEntity.settlement);
                data.Add("interestsubsidy", frm.DeliveryEntity.interestsubsidy);
                data.Add("tcamount", frm.DeliveryEntity.tcamount);
                data.Add("create_time", DateTime.Now);
                using (MySqlConnection connection = new MySqlConnection(Program.connectionString))
                {
                    // 打开连接
                    connection.Open();
                    MySqlTransaction transaction = connection.BeginTransaction();
                    //int result = MySQLHelper.Insert("tbl_delivery", data);
                    try
                    {
                        string sqlstr = "INSERT INTO tbl_delivery (" +
                        "salesman,companyname,deliverdate,salecount,saleamount,remainamount,perton,bsalary,accountdays,duedate,settlement," +
                        "interestsubsidy,tcamount,create_time" +
                    ") VALUES('" + data["salesman"].ToString() + "','" + data["companyname"].ToString() + "','" + data["deliverdate"].ToString() + "'," +
                        data["salecount"].ToString() + "," + data["saleamount"].ToString() + "," + data["remainamount"].ToString() + "," +
                        data["perton"].ToString() + "," + data["bsalary"].ToString() + "," + data["accountdays"].ToString() + ",'" +
                        data["duedate"].ToString() + "'," + data["settlement"].ToString() + "," + data["interestsubsidy"].ToString() + "," +
                        data["tcamount"].ToString() + ",'" + DateTime.Now + "');";

                        using (MySqlCommand cmd = new MySqlCommand(sqlstr, connection))
                        {
                            cmd.Transaction = transaction;
                            cmd.ExecuteNonQuery();
                        }
                        //判断有没有对应的预收款单，有的话自动开收款单
                        //获取预收款单
                        DataTable dt = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_receipt where parentid = -1 and companyname = '" + data["companyname"] + "' and salesman = '" + data["salesman"] + "'");
                        if (dt.Rows.Count > 0)
                        {
                            //获取刚才添加的送货单信息
                            DataRow dtrow = null;
                            using (MySqlCommand command = new MySqlCommand("SELECT * FROM tbl_delivery where companyname = '" + data["companyname"] + "' and salesman = '" + data["salesman"] + "' order by id desc limit 1", connection))
                            {
                                command.Transaction = transaction;
                                // 创建DataAdapter和DataTable对象，并填充数据
                                using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
                                {
                                    DataTable dt_deliver = new DataTable();
                                    adapter.Fill(dt_deliver);
                                    if (dt_deliver.Rows.Count > 0)
                                    {
                                        dtrow = dt_deliver.Rows[0];
                                    }
                                    else
                                    {
                                        this.ShowErrorDialog2("获取新建送货单数据异常，创建失败");
                                        transaction.Rollback();
                                        return;
                                    }
                                }
                            }
                            decimal amount = 0;//送货单收款余额
                            if (decimal.TryParse(dtrow["remainamount"].ToString(), out amount))
                            {
                                if (amount == 0)
                                {
                                    transaction.Rollback();
                                    return;
                                }
                                foreach (DataRow drow in dt.Rows)
                                {
                                    //判断预收款单金额是否小于等于送货单金额
                                    if (decimal.Parse(drow["receiptamount"].ToString()) <= amount)
                                    {
                                        //关联预收款单至该送货单，同时更新送货单收款余额
                                        using (MySqlCommand cmd = new MySqlCommand("update tbl_receipt set parentid = " + dtrow["id"].ToString() + " where id = " + drow["id"].ToString(), connection))
                                        {
                                            cmd.Transaction = transaction;
                                            cmd.ExecuteNonQuery();
                                            amount -= decimal.Parse(drow["receiptamount"].ToString());
                                        }
                                        using (MySqlCommand cmd = new MySqlCommand("update tbl_delivery set remainamount = " + amount + " where id = " + dtrow["id"].ToString(), connection))
                                        {
                                            cmd.Transaction = transaction;
                                            cmd.ExecuteNonQuery();
                                        }
                                    }
                                    else
                                    {
                                        //送货单被预收款单完全抵消
                                        using (MySqlCommand cmd = new MySqlCommand("update tbl_delivery set remainamount = 0 where id = " + dtrow["id"].ToString(), connection))
                                        {
                                            cmd.Transaction = transaction;
                                            cmd.ExecuteNonQuery();
                                        }
                                        //自动新增收款单
                                        Dictionary<string, object> auto_data = new Dictionary<string, object>();
                                        auto_data.Add("salesman", drow["salesman"].ToString());
                                        auto_data.Add("companyname", drow["companyname"].ToString());
                                        auto_data.Add("receiptdate", drow["receiptdate"].ToString());
                                        auto_data.Add("receiptway", drow["receiptway"].ToString());
                                        auto_data.Add("receiptamount", amount);
                                        auto_data.Add("overduedays", 0);
                                        auto_data.Add("interestrate", 0);
                                        auto_data.Add("interest", 0);
                                        auto_data.Add("create_time", DateTime.Now);
                                        sqlstr = "INSERT INTO tbl_receipt (" +
                                            "salesman,companyname,receiptdate,receiptway,receiptamount,overduedays,interestrate,interest,create_time,parentid" +
                                        ") VALUES('" + auto_data["salesman"].ToString() + "','" + auto_data["companyname"].ToString() + "','" + auto_data["receiptdate"].ToString() + "','" + auto_data["receiptway"].ToString() + "'," +
                                            auto_data["receiptamount"].ToString() + "," + auto_data["overduedays"].ToString() + "," + auto_data["interestrate"].ToString() + "," +
                                            auto_data["interest"].ToString() + ",'" + DateTime.Now + "'," + dtrow["id"].ToString() + ");";

                                        using (MySqlCommand cmd = new MySqlCommand(sqlstr, connection))
                                        {
                                            cmd.Transaction = transaction;
                                            cmd.ExecuteNonQuery();
                                        }
                                        //减去对应预收款单余额
                                        using (MySqlCommand cmd = new MySqlCommand("update tbl_receipt set receiptamount = " + (decimal.Parse(drow["receiptamount"].ToString()) - amount) + " where id = " + drow["id"].ToString(), connection))
                                        {
                                            cmd.Transaction = transaction;
                                            cmd.ExecuteNonQuery();
                                        }
                                    }
                                }

                            }
                            else
                            {
                                this.ShowErrorDialog2("异常的剩余结款数据:" + dtrow["remainamount"].ToString());
                                transaction.Rollback();
                                return;
                            }
                            this.ShowInfoDialog2("检测到存在预收款金额，已自动扣除收款金额并开具收款单，请核对.");
                        }
                    }
                    catch(Exception ex)
                    {
                        transaction.Rollback();
                        this.ShowErrorDialog2("处理过程出现异常:" + ex.Message);
                        return;
                    }
                    transaction.Commit();
                }
                ListQuery();

            }

            frm.Dispose();
        }

        private void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (uiDataGridView1.Columns[e.ColumnIndex].Name == "btn_del" && e.RowIndex >= 0)
            {
                if (uiDataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue.ToString() == "合计")
                {
                    return;
                }
                if (this.ShowAskDialog2("确定要删除该数据么?", true))
                {
                    DataGridViewRow vr = uiDataGridView1.Rows[e.RowIndex];
                    if(vr.Cells[4].Value.ToString() != vr.Cells[5].Value.ToString())
                    {
                        this.ShowErrorDialog2("该出货单已有收款单结算，不能删除.");
                        return;
                    }
                    int result = MySQLHelper.Delete("tbl_delivery", "id=" + vr.Cells[0].Value.ToString());
                    ListQuery();
                }
                
            }
            else if (uiDataGridView1.Columns[e.ColumnIndex].Name == "btn_edit" && e.RowIndex >= 0)
            {
                if (uiDataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue.ToString() == "合计")
                {
                    return;
                }
                DataGridViewRow vr = uiDataGridView1.Rows[e.RowIndex];
                DeliveryEntity delivery = new DeliveryEntity();
                delivery.id = long.Parse(vr.Cells[0].Value.ToString());
                delivery.salesman = vr.Cells[1].Value.ToString();
                delivery.companyname = vr.Cells[2].Value.ToString();
                delivery.deliverdate = DateTime.Parse(vr.Cells[3].Value.ToString());
                delivery.salecount = double.Parse(vr.Cells[4].Value.ToString());
                delivery.saleamount = decimal.Parse(vr.Cells[5].Value.ToString());
                delivery.remainamount = decimal.Parse(vr.Cells[6].Value.ToString());
                delivery.perton = double.Parse(vr.Cells[7].Value.ToString());
                delivery.bsalary = double.Parse(vr.Cells[8].Value.ToString());
                delivery.accountdays = int.Parse(vr.Cells[9].Value.ToString());
                delivery.duedate = DateTime.Parse(vr.Cells[10].Value.ToString());
                delivery.settlement = double.Parse(vr.Cells[11].Value.ToString());
                delivery.interestsubsidy = double.Parse(vr.Cells[12].Value.ToString());
                delivery.tcamount = double.Parse(vr.Cells[13].Value.ToString());
                DeliveryDialog frm = new DeliveryDialog();
                frm.Render();
                decimal osaleamount = delivery.saleamount;
                frm.DeliveryEntity = delivery;
                frm.ShowDialog();
                if (frm.IsOK)
                {
                    // 更新数据
                    Dictionary<string, object> data = new Dictionary<string, object>();
                    data.Add("salesman", frm.DeliveryEntity.salesman);
                    data.Add("companyname", frm.DeliveryEntity.companyname);
                    data.Add("deliverdate", frm.DeliveryEntity.deliverdate);
                    data.Add("salecount", frm.DeliveryEntity.salecount);
                    data.Add("saleamount", frm.DeliveryEntity.saleamount);
                    data.Add("perton", frm.DeliveryEntity.perton);
                    data.Add("bsalary", frm.DeliveryEntity.bsalary);
                    data.Add("accountdays", frm.DeliveryEntity.accountdays);
                    data.Add("duedate", frm.DeliveryEntity.duedate);
                    data.Add("settlement", frm.DeliveryEntity.settlement);
                    data.Add("interestsubsidy", frm.DeliveryEntity.interestsubsidy);
                    data.Add("tcamount", frm.DeliveryEntity.tcamount);
                    //判断销售金额是否有变动
                    if(osaleamount != frm.DeliveryEntity.saleamount)
                    {
                        data.Add("remainamount", delivery.remainamount + frm.DeliveryEntity.saleamount - osaleamount);
                    }
                    int result = MySQLHelper.Update("tbl_delivery", data, "id=" + frm.DeliveryEntity.id);
                    ListQuery();
                }

                frm.Dispose();
            }
        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            ListQuery();
        }

        private void DeliveryInvoice_Initialize(object sender, EventArgs e)
        {
            dt_qend.Value = DateTime.Now;
            dt_qstart.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            ListQuery();
        }

        private void uiDataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex > -1 && e.RowIndex > -1)
            {
                // 检查是否是按钮列
                if (uiDataGridView1.Columns[e.ColumnIndex].Name == "btn_del" || uiDataGridView1.Columns[e.ColumnIndex].Name == "btn_edit")
                {
                    if ((e.ColumnIndex == 15 || e.ColumnIndex == 16) && uiDataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue.ToString() == "合计")
                    {
                        // 跳过绘制按钮
                        e.Handled = true;
                    }
                }
            }
        }
    }
}
